﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HouodeFun.TrainCenter.Model;
using System.Data.Objects;
using HouodeFun.TrainCenter.IDAL;

namespace HouodeFun.TrainCenter.DAL
{
    public class BaseRepository<T> where T :class,new()
    {
        private ObjectContext db;

        public BaseRepository()
        {
            IObjectContextFactory tempFactory = new ObjectContextFactory();
            db = tempFactory.GetCurrentThreadInstance();
        }

        //批量添加  100000000
        public virtual int AddEnties(params T[] entities)
        {
            int result = 0;

            for (int i = 0; i < entities.Count(); i++)
            {
                if (entities[i] == null)
                {
                    continue;
                }

                //db.UserInfo.AddObject(entities[i]);

                db.CreateObjectSet<T>().AddObject(entities[i]);
                if (i % 20 == 0 && i != 0)//每 20 条数据就提交一次
                {
                    result += db.SaveChanges();
                }
            }

            if (entities.Count() > 0)
            {
                result += db.SaveChanges();
            }

            return result;
        }

        public virtual T AddEntity(T entity)
        {
            //User Id:自动增长，
            //单元测试：
            //DataModelContainer db = new DataModelContainer();

            //var tempFactory = new ObjectContextFactory();
            //ObjectContext db = tempFactory.GetCurrentThreadInstance();
            
            //db.UserInfo.AddObject(entity);

            db.CreateObjectSet<T>().AddObject(entity);

            
            //db.SaveChanges();

            return entity;
        }

        public virtual int DeleteEntity(T entity)
        {
            //DataModelContainer db = new DataModelContainer();

            //var tempFactory = new ObjectContextFactory();
            //ObjectContext db = tempFactory.GetCurrentThreadInstance();

            //db.UserInfo.Attach(user);//内部会帮帮我们自动创建EntityKey
            //db.Attach(user);//必须自己指定EntityKey

            //改变实体的状态

            db.CreateObjectSet<T>().Attach(entity);

            db.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Deleted);
            //return db.SaveChanges();
            return -1;
        }

        #region MyRegion       
       
        //public class UserInfoService
        //{
        //    public int DeleteUserInfo()
        //    {
        //        DbSession db = new DbSession();
        //        //db.SaveChange();

        //        db.UserInfoRepository.DeleteEntity(new UserInfo() { ID=100});
        //        db.UserInfoRepository.AddEntity(new UserInfo() { });

        //        int i= db.SaveChange();
        //    }

        //}
        #endregion


        public virtual int DeleteBy(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            //DataModelContainer db = new DataModelContainer();


            //var tempFactory = new ObjectContextFactory();
            //ObjectContext db = tempFactory.GetCurrentThreadInstance();


            var temp = db.CreateObjectSet<T>().Where<T>(whereLambda);
            //var temp = db.UserInfo.Where<UserInfo>(whereLambda);
            foreach (var item in temp)
            {
                db.CreateObjectSet<T>().DeleteObject(item);
            }
            //return db.SaveChanges();
            return -1;
        }

        public virtual T UpdateEntity(T entity)
        {
            if (entity != null)
            {
                //DataModelContainer db = new DataModelContainer();

                //var tempFactory = new ObjectContextFactory();
                //ObjectContext db = tempFactory.GetCurrentThreadInstance();

                db.CreateObjectSet<T>().Attach(entity);
                db.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);

                //if (db.SaveChanges() <= 0)
                //{
                //    return null;
                //}
            }
            return entity;
        }


        public virtual IQueryable<T> LoadEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            //DataModelContainer db = new DataModelContainer();//
            //var tempFactory = new ObjectContextFactory();
            //ObjectContext db = tempFactory.GetCurrentThreadInstance();
            IQueryable<T> temp = db.CreateObjectSet<T>().Where<T>(whereLambda);//.AsQueryable<UserInfo>();
            return temp;
        }


        /// <summary>
        /// 通用分页方法
        /// </summary>
        /// <typeparam name="S"></typeparam>
        /// <param name="whereLambda"></param>
        /// <param name="orderBy"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="totalCount"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public virtual IQueryable<T> LoadPageEntities<S>(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, S>> orderBy, int pageSize, int pageIndex, out int totalCount, bool isAsc)
        {
            //必须有：请求当前页，页的大小 ， 总页数  过滤条件

            //DataModelContainer db = new DataModelContainer();
            totalCount = db.CreateObjectSet<T>().Where<T>(whereLambda).Count();

            IQueryable<T> enties = null;

            if (isAsc)//这是升序
            {
                enties = db.CreateObjectSet<T>()
                    .Where<T>(whereLambda)
                    //.OrderBy<UserInfo,int>(u=>u.ID)
                    .OrderBy<T, S>(orderBy)   //语法糖
                    .Skip<T>(pageSize * (pageIndex - 1))
                    .Take<T>(pageSize);

            }
            else
            {
                enties = db.CreateObjectSet<T>()//降序查询
                   .Where<T>(whereLambda)
                    //.OrderBy<UserInfo,int>(u=>u.ID)
                   .OrderByDescending<T, S>(orderBy)   //语法糖
                   .Skip<T>(pageSize * (pageIndex - 1))
                   .Take<T>(pageSize);

            }
            return enties;

        }
    }
}
